const express = require('express')
const router = express.Router()
const Goods = require('../db/goods')
const User = require('../db/users')
const Cart = require('../db/cart')
const jwt = require('jsonwebtoken')
//购物车添加数据
router.post('/api/addCart', (req, res) => {
  let id = req.body.goodsId
  let token = req.headers.authorization
  new Promise((resolved, rejected) => {
    resolved(jwt.verify(token, 'jwt'))
  }).then(val => {
    let tel = val.tel
    //获取用户id
    let uId
    User.find({
      tel
    }).then(userInfo => {
      uId = userInfo[0]._id
      //通过uId查询该用户的购物车数据
      Cart.find({
        uId
      }).then(cartData => {
        //该用户是否有购物车数据
        if (cartData[0]) {
          //有购物车数据，查询是否有同类商品
          let id_
          cartData.forEach((v, i) => {
            if (v.goods_id == id) {
              id_ = i
            }
          })
          if (id_ == undefined) {
            //没有就创建
            //通过商品id查询商品数据
            Goods.find({
              id
            }).then(goodsList => {
              //创建购物车数据
              let goods_id = goodsList[0].id
              let goods_name = goodsList[0].name
              let goods_price = goodsList[0].price
              let goods_imgUrl = goodsList[0].imgUrl
              Cart.create({
                uId,
                goods_id,
                goods_name,
                goods_price,
                goods_imgUrl
              }).then(data => {
                return res.send({
                  code: 200,
                  success: true,
                  msg: '加入购物车成功',
                  data: data[0]
                })
              })
            })
          } else {
            //有则增加数量
            let nowData = cartData[id_]
            nowData.goods_num += 1
            Cart.updateMany({
              _id: nowData._id
            }, {
              goods_num: nowData.goods_num
            }).then(updata => {
              return res.send({
                code: 200,
                msg: '购物车添加成功',
                success: true
              })
            })
          }
        } else {
          //没有就创建
          //通过商品id查询商品数据
          Goods.find({
            id
          }).then(goodsList => {
            //创建购物车数据
            let goods_id = goodsList[0].id
            let goods_name = goodsList[0].name
            let goods_price = goodsList[0].price
            let goods_imgUrl = goodsList[0].imgUrl
            Cart.create({
              uId,
              goods_id,
              goods_name,
              goods_price,
              goods_imgUrl
            }).then(data => {
              return res.send({
                code: 200,
                success: true,
                msg: '加入购物车成功',
                data: data[0]
              })
            })
          })
        }
      })
    })
  }).catch(err => {
    return res.send({
      code: 400,
      msg: err.message
    })
  })
})
//查询购物车数据
router.post('/api/selectCart', (req, res) => {
  let token = req.headers.authorization
  new Promise((resolved, rejected) => {
    resolved(jwt.verify(token, 'jwt'))
  }).then(val => {
    let tel = val.tel
    //获取用户id,商品信息
    let uId
    User.find({
      tel
    }).then(userInfo => {
      uId = userInfo[0]._id
    }).then(() => {
      Cart.find({
        uId
      }).then(data => {
        return res.send({
          code: 200,
          success: true,
          data
        })
      })
    })
  }).catch(err => {
    return res.send({
      code: 400,
      msg: err.message
    })
  })
})
//删除购物车数据
router.post('/api/deleteCart', (req, res) => {
  let token = req.headers.authorization
  let goods_id = req.body['goodsId[]']
  new Promise((resolved, rejected) => {
    resolved(jwt.verify(token, 'jwt'))
  }).then(() => {
    goods_id = Array.isArray(goods_id) ? goods_id : [goods_id]
    goods_id.forEach((goods_id, index) => {
      Cart.deleteMany({
        goods_id
      }, (err, info) => {
        if (err) return
        if (index + 1 == goods_id.length) {
          res.send({
            code: 200,
            msg: '删除成功',
            success: true
          })
        }
      })
    })
  }).catch(err => {
    return res.send({
      code: 400,
      msg: err.message
    })
  })
})
//改变购物车数量
router.post('/api/updateNum', (req, res) => {
  let token = req.headers.authorization
  let num = req.body.num
  let id = req.body.id
  new Promise((resolved, rejected) => {
    resolved(jwt.verify(token, 'jwt'))
  }).then(() => {
    Cart.updateMany({
      goods_id: id
    }, {
      goods_num: num
    }).then(data => {
      return res.send({
        code: 200,
        success: true,
        data
      })
    })
  }).catch(err => {
    return res.send({
      code: 400,
      msg: err.message
    })
  })
})
module.exports = router
